package Models.dao;

import Models.enity.Announcement;
import Models.utils.DataSourceManager;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class AnnouncementDao {
    private QueryRunner runner = new QueryRunner(DataSourceManager.getDataSource());

    public List<Announcement> findRecentlyWeeks(){
        String sql = "SELECT * FROM announcement WHERE YEARWEEK(date_format(created_at,'%Y-%m-%d')) = YEARWEEK(now()) order by created_at DESC";
        try {
            return runner.query(sql,new BeanListHandler<Announcement>(Announcement.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  null;
    }

    public List<Announcement> findAll(){
        String sql = "SELECT * FROM announcement order by created_at DESC";
        try {
            return runner.query(sql,new BeanListHandler<Announcement>(Announcement.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public long findDataSize(){
        String sql = "SELECT count(id) FROM announcement";
        try {
            return runner.query(sql,new ScalarHandler<Long>());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new Long(-1L);
    }
    public List<Announcement> findPaginationData(int skip,int pageSize){
        String sql = "SELECT * FROM announcement limit ?,?";
        try {
            return runner.query(sql,new BeanListHandler<Announcement>(Announcement.class),skip,pageSize);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int insert(String content,String department,String created_at){
        String sql ="INSERT INTO announcement(content,department,created_at) VALUES (?,?,?)";
        try {
            return runner.update(sql,content,department,created_at);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  -1;
    }

    public int delete(String id){
        String sql = "DELETE FROM announcement WHERE id=?";
        try {
            return runner.update(sql,id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }
}
